<template>
    <div>
        <el-dialog
                :visible.sync="visible"
                width="700px"
                :before-close="handleClose"
                class="box-card">
            <div class="title">
                <i class="el-icon-edit"> {{ title }}</i>
            </div>
            <br>
            <el-form
                    ref="formRef"
                    :rules="rules"
                    :model="formData"
                    label-width="120px"
                    label-position="right"
                    style="width: 90%"
                    status-icon>
                <el-form-item label="网站名称" prop="name">
                    <el-input v-model.trim="formData.name" maxlength="30" clearable show-word-limit/>
                </el-form-item>
                <el-form-item label="网站链接地址" prop="url">
                    <el-input v-model.trim="formData.url" maxlength="200" clearable show-word-limit/>
                </el-form-item>
                <el-form-item label="网站logo">
                    <div class="upload-image-container" @click="showAvatarDialog">
                        <i class="el-icon-plus icon" v-if="formData.logo === ''"></i>
                        <img fit="cover" v-if="formData.logo" :src="formData.logo" class="avatar"/>
                    </div>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model.trim="formData.sort" :min="1" :max="1000">
                    </el-input-number>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-select v-model.trim="formData.state" clearable style="width:185px">
                        <el-option label="正常" value="1"></el-option>
                        <el-option label="不可用" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item align="right">
                    <el-button @click="handleClose" size="mini">取消</el-button>
                    <el-button @click="resetForm('formRef')" size="mini">重置</el-button>
                    <el-button type="primary" @click="submitForm('formRef')" size="mini">确定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!--  field="file" 后台文件名 ; url="/admin/image" 后台上传图片的接口地址 -->
        <avatar-upload field="file"
                       @crop-upload-success="cropUploadSuccess"
                       @crop-upload-fail="cropUploadFail"
                       v-model.trim="showAvatarCutter"
                       :width="300"
                       :height="300"
                       url="/admin/image/link"
                       img-format="png"></avatar-upload>
    </div>
</template>

<script>
    import avatarUpload from 'vue-image-crop-upload/upload-2.vue';
    import {addFriendLink,updateFriendLink} from '@/api/api'

    export default {
        components: {
            'avatar-upload': avatarUpload
        },
        props: {
            title: { // 弹窗的标题
                type: String,
                default: ''
            },
            visible: { // 弹出窗口，true弹出
                type: Boolean,
                default: false
            },
            formData: { // 提交表单数据对象
                type: Object,
                default: () => { // 对象或数组默认值必须从一个工厂函数获取
                    return {}
                }
            },
            remoteClose: Function // 用于关闭窗口
        },
        data() {
            return {
                showAvatarCutter: false,
                // 校验表单数据
                rules: {
                    name: [
                        {required: true, message: '友情链接名不能为空', trigger: 'blur'},
                        {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
                    ],
                    logo: [
                        {required: true, message: ' logo不能为空', trigger: 'blur'},
                        {
                            // eslint-disable-next-line no-useless-escape
                            pattern: /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
                            message: 'logo地址格式不正确',
                            trigger: 'blur'
                        }
                    ],
                    url: [
                        {required: true, message: '网站地址不能为空', trigger: 'blur'},
                        {
                            // eslint-disable-next-line no-useless-escape
                            pattern: /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
                            message: '链接地址格式不正确',
                            trigger: 'blur'
                        }
                    ]
                }

            }
        },
        methods: {
            // 打开上传框架组件
            showAvatarDialog() {
                this.showAvatarCutter = true
            },
            // 上传成功（用户头像）
            cropUploadSuccess(response) {
                // console.log(status, field)
                // console.log(field)
                if (response.code === 20000) {
                    this.$message.success(response.message)
                    // 回显头像
                    // http://localhost:2021/admin/image/1639041576000_9364dbcce6c04a17a315e59839334fab.png
                    this.formData.logo = this.blog_constant.baseUrl+'/admin/image/' + response.data.id;
                    this.showAvatarCutter = false
                } else {
                    this.$message.error(response.message)
                }
            },
            // 上传失败
            cropUploadFail() {
                this.$message.error('上传失败')
            },

            // 取消(关闭窗口,清空表单和校验结果)
            handleClose() {
                this.$refs['formRef'].resetFields()
                // 注意不可以通过  this.visible = false来关闭，因为它是父组件的属性
                this.remoteClose()
            },
            // 重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields()
            },

            // 提交表单数据
            submitForm(formRef) {
                this.$refs[formRef].validate((valid) => {
                    if (valid) {
                        // 校验通过，提交表单数据
                        this.addOrUpdate()
                    } else {
                        return false
                    }
                })
            },
            // 添加或更新
            async addOrUpdate() {
                let response = null
                // 有 id 为更新
                if (this.formData.id) {
                    response = await updateFriendLink(this.formData)
                    if (response.code === 20000) {
                        this.$message.success(response.message)
                        // 关闭窗口
                        this.handleClose()
                    } else {
                        this.$message.error(response.message)
                    }
                } else {
                    // 没 id 为添加
                    response = await addFriendLink(this.formData)
                    if (response.code === 20000) {
                        this.$message.success(response.message)
                        // 关闭窗口
                        this.handleClose()
                    } else {
                        this.$message.error(response.message)
                    }
                }
            }

        }
    }
</script>
<style>
    .title {
        font-size: 22px;
        text-align: center;
        margin-bottom: 20px;
    }

    .upload-image-container, .avatar {
        width: 178px;
        height: 178px;
        display: block;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;

    }

    .upload-image-container {

    }

    .icon {
        font-size: 40px;
        color: #c1c1c1;
        position: absolute;
        left: 70px;
        top: 70px;

    }

</style>